package com.haoyeteng.sxbd.core.base.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.haoyeteng.sxbd.core.mongodb.MongoFileReader;
import com.haoyeteng.sxbd.core.util.WebUtils;
import com.mongodb.gridfs.GridFSDBFile;

@Controller
@RequestMapping("/static")
public class MongoFileReaderController {

	@Autowired
	private MongoFileReader mongoFileReader;

	@RequestMapping("file/{fileid}")
	public void loadFileById(@PathVariable("fileid") String fileid, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (null == fileid) {
			return;
		}
    	GridFSDBFile gridFSDBFile = mongoFileReader.toRead(fileid);
    	//InputStream is = gridFSDBFile.getInputStream();
		if (null != gridFSDBFile) {

			response.setContentType(gridFSDBFile.getContentType());
			String fileName = WebUtils.encodeFileName(request, gridFSDBFile.getFilename());
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			response.setHeader("Content-Length", String.valueOf(gridFSDBFile.getLength()));
			OutputStream stream = response.getOutputStream();
			gridFSDBFile.writeTo(stream);
			stream.flush();
			stream.close();
		}
        /*
         String referer=request.getHeader("referer"); 
         if(referer==null||!referer.startsWith("http://localhost")){  
        	response.sendRedirect(request.getContextPath() + "/portal/index.shtml");  
        }else{
        	if (null == fileid) {
    			return;
    		}
        	GridFSDBFile gridFSDBFile = mongoFileReader.toRead(fileid);
    		if (null != gridFSDBFile) {

    			response.setContentType(gridFSDBFile.getContentType());
    			String fileName = WebUtils.encodeFileName(request, gridFSDBFile.getFilename());
    			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
    			response.setHeader("Content-Length", String.valueOf(gridFSDBFile.getLength()));
    			OutputStream stream = response.getOutputStream();
    			gridFSDBFile.writeTo(stream);
    			stream.flush();
    			stream.close();
    		}
        } 
        */
	}
}
